package utils

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/httplib"
	"lz/global"
	"strconv"
	"time"
)

var (
	postPath   = "/api/send"   //发送接口
	statusPath = "/api/status" //"/api/status" //消息状态查询接口
	uploadPath = "/upload"
)

// 推送是否是生成模式
var pushProductionMode = "true"

// 设置前端收到通知后点击通知跳转的页面（这个是前端给的）
var pushAndroidActityChat = "xxx"
var pushAndroidActivityWeb = "xxx"

type YouMsgData struct {
	Type      int8   // 推送类型 1为 别名推送 2 为 token推送
	Val       string // 1 Type 为1 Device 值为别名值 2 为device_token 值
	UType     string //友盟推送类型 见官方文档
	AliasType string //如果是别名推送需要传递此类型,见官方文档
}

// ========================================
type UmengAdroid struct {
	Appkey    string `json:"appkey"`    // 必填项
	Timestamp string `json:"timestamp"` // 必填项
	Type      string `json:"type"`      // 必填项

	DeviceTokens    string          `json:"device_tokens"` // 选填,用于给特定设备的推送
	AliasType       string          `json:"alias_type"`
	Alias           string          `json:"alias"`
	FileId          string          `json:"file_id"`
	Production_mode string          `json:"production_mode"`
	Payload         *PayloadAndroid `json:"payload"` // 必填项
	Description     string          `json:"description"`
}

type PayloadAndroid struct {
	Display_type string            `json:"display_type"` // 必填项
	Body         *BodyAndroid      `json:"body"`         // 必填项
	Extral       map[string]string `json:"extra"`
}
type BodyAndroid struct {
	Ticker     string `json:"ticker"`     // 必填项
	Title      string `json:"title"`      // 必填项
	Text       string `json:"text"`       // 必填项
	After_open string `json:"after_open"` // 必填项
	Activity   string `json:"activity"`   // 必填项
}

// PushAndroid android推送 deviceToken:设备的编号,如果设置deviceToken，则是单播;如果未设置则是全播
func PushAndroid(title string, deviceToken, fileId string, extralDatas map[string]string) ([]byte, error) {

	body := &BodyAndroid{
		Ticker:     title,
		Title:      title,
		Text:       title,
		After_open: "go_activity",
		Activity:   pushAndroidActityChat,
	}

	payLoad := &PayloadAndroid{}
	payLoad.Display_type = "notification"
	payLoad.Body = body
	/*
	   额外携带的信息
	*/
	payLoad.Extral = extralDatas

	messageAndroid := UmengAdroid{}
	messageAndroid.Appkey = global.ServerConfig.Umeng.AndroidKey

	// 打开聊天
	//body.Activity = pushAndroidActityChat
	if deviceToken == "" {

		// 全播
		messageAndroid.Type = "customizedcast" //"broadcast"
		messageAndroid.AliasType = "file_id"
		//messageAndroid.Alias = "25fcbfdd4a47630c3bb6dabb85c53b401"
		messageAndroid.FileId = fileId
	} else {

		// 单播
		messageAndroid.Type = "unicast"
		messageAndroid.DeviceTokens = deviceToken

	}

	//当前时间戳
	timeInt64 := time.Now().Unix()
	timestamp := strconv.FormatInt(timeInt64, 10)

	messageAndroid.Timestamp = timestamp
	messageAndroid.Production_mode = pushProductionMode
	messageAndroid.Payload = payLoad
	messageAndroid.Description = title

	postBody, _ := json.Marshal(messageAndroid)
	url := global.ServerConfig.Umeng.Host + postPath

	// MD5加密
	sign := Md5("POST" + url + string(postBody) + global.ServerConfig.Umeng.AndroidSecrept)
	url = url + "?sign=" + sign

	req := httplib.Post(url)

	req.JSONBody(messageAndroid)
	byteData, err := req.Bytes()

	return byteData, err

}

type YoumengStatus struct {
	AppKey    string `json:"appkey"`    // 必填项
	Timestamp string `json:"timestamp"` // 必填项
	TaskId    string `json:"task_id"`   // 必填项
}

func PushStatus(appKey, taskId, secrept string) ([]byte, error) {

	timeInt64 := time.Now().Unix()
	timestamp := strconv.FormatInt(timeInt64, 10)
	data := &YoumengStatus{
		AppKey:    appKey,
		Timestamp: timestamp,
		TaskId:    taskId,
	}
	postBody, _ := json.Marshal(data)
	url := global.ServerConfig.Umeng.Host + postPath

	// MD5加密
	sign := Md5("POST" + url + string(postBody) + secrept)
	url = url + "?sign=" + sign

	req := httplib.Post(url)

	req.JSONBody(data)
	byteData, err := req.Bytes()

	return byteData, err
}

type YoumengUpload struct {
	AppKey    string `json:"appkey"`    // 必填项
	Timestamp string `json:"timestamp"` // 必填项
	Content   string `json:"content"`   // 必填项
}

// PushUpload 友盟上传文件
func PushUpload(appKey, content, secrept string) ([]byte, error) {

	timeInt64 := time.Now().Unix()
	timestamp := strconv.FormatInt(timeInt64, 10)
	data := &YoumengUpload{
		AppKey:    appKey,
		Timestamp: timestamp,
		Content:   content,
	}
	postBody, _ := json.Marshal(data)
	url := global.ServerConfig.Umeng.Host + uploadPath

	// MD5加密
	sign := Md5("POST" + url + string(postBody) + secrept)
	url = url + "?sign=" + sign

	req := httplib.Post(url)

	req.JSONBody(data)
	byteData, err := req.Bytes()

	return byteData, err
}

//=============================================================================================
/**
IOS推送必须项:
appkey
"timestamp":"xx",       // 必填 时间戳，10位或者13位均可，时间戳有效期为10分钟
type       //broadcast
"alert": "xx"          // 必填
MasterSecret
"production_mode":"true/false" // 可选 正式/测试模式。测试模式下，只会将消息发给测试设备。
*/

var PushIOSTypeAdd = 1000

type UmengIOS struct {
	Appkey          string      `json:"appkey"`    // 必填项
	Timestamp       string      `json:"timestamp"` // 必填项
	Type            string      `json:"type"`      // 必填项
	Production_mode string      `json:"production_mode"`
	Payload         *PayloadIOS `json:"payload"`       // 必填项
	Devicetokens    string      `json:"device_tokens"` // 选填项
	Description     string      `json:"description"`
}

type PayloadIOS struct {
	Aps   *ApsIOS `json:"aps"`
	Ptype int     `json:"ptype"` // 1000:咨询,1001:政策法规;1004:法制宣传;1013:新闻
	Purl  string  `json:"purl"`
}

type ApsIOS struct {
	Alert             string `json:"alert"` // 必填项
	Content_available string `json:"content-available"`
}

// IOS推送
// deviceToken:设备的编号,如果设置deviceToken，则是单播;如果未设置则是全播
// ptype,purl:额外参数，非必选值
// ptype:区分类型
// purl:要打开的超链接的类型
func Push_IOS(title string, deviceToken string, ptype int, purl string) {

	aps := &ApsIOS{}
	aps.Alert = "xxx"
	aps.Content_available = title

	payLoad := &PayloadIOS{}
	payLoad.Aps = aps
	payLoad.Ptype = ptype
	payLoad.Purl = purl

	messageIOS := UmengIOS{}
	messageIOS.Payload = payLoad
	messageIOS.Appkey = global.ServerConfig.Umeng.IosKey
	timeInt64 := time.Now().Unix()
	timestamp := strconv.FormatInt(timeInt64, 10)
	messageIOS.Timestamp = timestamp

	// 通过判断是否设置 deviceToken，来区分 单播 和 全播
	if deviceToken == "" {
		// 全播
		messageIOS.Type = "broadcast"
	} else {

		// 单播
		messageIOS.Type = "unicast"
		messageIOS.Devicetokens = deviceToken
	}

	messageIOS.Production_mode = pushProductionMode
	messageIOS.Description = title

	postBody, _ := json.Marshal(messageIOS)
	url := global.ServerConfig.Umeng.Host + postPath

	// MD5加密
	sign := Md5("POST" + url + string(postBody) + global.ServerConfig.Umeng.IosSecrept)
	url = url + "?sign=" + sign

	req := httplib.Post(url)
	req.JSONBody(messageIOS)

	byteData, err := req.Bytes()
	if err != nil {
		fmt.Println("ios err back,", err, url)
	} else {
		strData := string(byteData)
		fmt.Println(" ios back,", strData)
	}
}

// md5加密
func Md5(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	sStr := hex.EncodeToString(h.Sum(nil))
	return sStr
}
